import { z } from "zod";
import { codeartsrepoRequest, buildUrl } from "../common/utils.js";
import { RepoMemberSchema } from "../common/types.js";

// 获取仓库所有成员记录
export const ListRepoMembersSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
  search: z.string().optional().describe("搜索关键词"),
  page: z.number().optional().describe("页码，默认为1"),
  per_page: z.number().optional().describe("每页数量，默认为20"),
});

// 添加仓库成员
export const AddRepoMembersSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
  user_ids: z.array(z.string()).describe("用户ID列表"),
  access_level: z.number().describe("访问级别: 10=读者, 20=开发者, 30=维护者, 40=所有者"),
});

// 设置成员在仓库中的角色
export const SetRepoRoleSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
  user_id: z.string().describe("用户ID"),
  access_level: z.number().describe("访问级别: 10=读者, 20=开发者, 30=维护者, 40=所有者"),
});

// 删除仓库成员
export const DeleteRepoMemberSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
  user_id: z.string().describe("用户ID"),
});

// 功能实现
export async function listRepoMembers(
  projectId: string,
  repoId: string,
  search?: string,
  page: number = 1,
  perPage: number = 20
) {
  const url = buildUrl(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/members`, {
    search,
    page,
    per_page: perPage
  });

  const response = await codeartsrepoRequest(url);
  return z.array(RepoMemberSchema).parse(response);
}

export async function addRepoMembers(
  projectId: string,
  repoId: string,
  userIds: string[],
  accessLevel: number
) {
  const response = await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/members`, {
    method: "POST",
    body: {
      user_ids: userIds,
      access_level: accessLevel
    }
  });
  
  return z.array(RepoMemberSchema).parse(response);
}

export async function setRepoRole(
  projectId: string,
  repoId: string,
  userId: string,
  accessLevel: number
) {
  const response = await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/members/${userId}`, {
    method: "PUT",
    body: {
      access_level: accessLevel
    }
  });
  
  return RepoMemberSchema.parse(response);
}

export async function deleteRepoMember(
  projectId: string,
  repoId: string,
  userId: string
) {
  await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/members/${userId}`, {
    method: "DELETE"
  });
  
  return { success: true };
} 